<template>
  <div class="agent-layout">
    <!-- 左侧导航菜单 -->
    <div class="sidebar" :class="{ 'collapsed': isCollapsed }">
      <div class="logo">
        <h2 v-if="!isCollapsed">COKFOOD</h2>
        <h2 v-else>CF</h2>
      </div>
      <div class="menu">
        <div v-for="item in menuItems" :key="item.path" class="menu-item" :class="{
          'active': isActive(item),
          'has-children': item.children && item.children.length
        }">
          <div class="menu-item-title"
            @click="item.children && item.children.length ? toggleSubmenu(item) : navigateTo(item.path)">
            <i :class="['icon', `fa-${item.icon}`]"></i>
            <span v-if="!isCollapsed">{{ item.title }}</span>
            <i v-if="!isCollapsed && item.children && item.children.length"
              :class="['submenu-arrow', openedMenus.includes(item.path) ? 'fa-angle-down' : 'fa-angle-right']"></i>
          </div>

          <div v-if="!isCollapsed && item.children && item.children.length" class="submenu"
            v-show="openedMenus.includes(item.path)">
            <div v-for="subItem in item.children" :key="subItem.path" class="submenu-item"
              :class="{ 'active': isActive(subItem) }" @click="navigateTo(subItem.path)">
              <i v-if="subItem.icon" :class="['icon', `fa-${subItem.icon}`]"></i>
              <span>{{ subItem.title }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="collapse-button" @click="toggleCollapse">
        <i :class="['icon', isCollapsed ? 'fa-angle-right' : 'fa-angle-left']"></i>
      </div>
    </div>

    <!-- 右侧内容区域 -->
    <div class="main-content">
      <!-- 顶部标题栏 -->
      <div class="header">
        <div class="breadcrumb">
          <span v-for="(item, index) in breadcrumbs" :key="index">
            <span class="breadcrumb-item" :class="{ 'clickable': index < breadcrumbs.length - 1 }"
              @click="index < breadcrumbs.length - 1 ? navigateTo(item.path) : null">
              {{ item.title }}
            </span>
            <span v-if="index < breadcrumbs.length - 1" class="breadcrumb-separator">/</span>
          </span>
        </div>
        <div class="user-info">
          <div class="dropdown">
            <span class="username" @click="toggleUserDropdown">区域代理 <i class="icon fa-angle-down"></i></span>
            <div class="dropdown-menu" v-show="isUserDropdownOpen">
              <div class="dropdown-item" @click="viewProfile">
                <i class="icon fa-user"></i> 个人信息
              </div>
              <div class="dropdown-item" @click="viewSettings">
                <i class="icon fa-cog"></i> 账户设置
              </div>
              <div class="dropdown-divider"></div>
              <div class="dropdown-item" @click="logout">
                <i class="icon fa-sign-out-alt"></i> 退出登录
              </div>
            </div>
          </div>
          <div class="avatar">
            <img src="https://via.placeholder.com/40" alt="用户头像">
          </div>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="content">
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <keep-alive>
              <component :is="Component" />
            </keep-alive>
          </transition>
        </router-view>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAgentStore } from '@/stores/agent'

interface MenuItem {
  title: string;
  path: string;
  icon: string;
  children?: MenuItem[];
}

interface BreadcrumbItem {
  title: string;
  path: string;
}

const router = useRouter()
const route = useRoute()
const agentStore = useAgentStore()

// 菜单折叠状态
const isCollapsed = ref(false)

// 打开的子菜单状态
const openedMenus = ref<string[]>([])

// 用户下拉菜单状态
const isUserDropdownOpen = ref(false)

// 当前激活路径
const currentPath = computed(() => route.path)

// 生成面包屑
const breadcrumbs = computed(() => {
  const result: BreadcrumbItem[] = [{ title: '首页', path: '/agent' }]
  const matched = route.matched

  if (matched.length) {
    for (let i = 1; i < matched.length; i++) {
      const item = matched[i]
      if (item.meta && item.meta.title) {
        const title = typeof item.meta.title === 'string'
          ? item.meta.title
          : 'Unknown'

        const parts = title.split('-')
        const cleanTitle = parts.length > 1 ? parts[1].trim() : parts[0].trim()

        result.push({
          title: cleanTitle,
          path: item.path
        })
      }
    }
  }

  return result
})

// 判断菜单项是否激活
const isActive = (item: MenuItem): boolean => {
  if (item.path === currentPath.value) return true
  if (item.children) {
    return item.children.some(child => child.path === currentPath.value)
  }
  return false
}

// 菜单项配置，包含子菜单支持
const menuItems: MenuItem[] = [
  {
    title: '控制台',
    path: '/agent/dashboard',
    icon: 'tachometer-alt'
  },
  {
    title: '分销商管理',
    path: '/agent/distributors',
    icon: 'users'
  },
  {
    title: '订单管理',
    path: '/agent/orders',
    icon: 'shopping-cart'
  },
  {
    title: '佣金管理',
    path: '/agent/commission',
    icon: 'wallet',
    children: [
      {
        title: '佣金明细',
        path: '/agent/commission/records',
        icon: 'list-alt'
      },
      {
        title: '佣金提现',
        path: '/agent/commission/withdraw',
        icon: 'money-bill-wave'
      },
    ]
  },
  {
    title: '打粉管理',
    path: '/agent/finance/FansPage',
    icon: 'chart-bar'
  },
  // {
  //   title: '账户设置',
  //   path: '/agent/profile',
  //   icon: 'cog'
  // }
]

// 切换菜单折叠状态
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
  // 将折叠状态保存到本地存储中，以便页面刷新后保持状态
  localStorage.setItem('agentMenuCollapsed', isCollapsed.value.toString())
}

// 切换子菜单展开状态
const toggleSubmenu = (item: MenuItem) => {
  const index = openedMenus.value.indexOf(item.path)
  if (index > -1) {
    openedMenus.value.splice(index, 1)
  } else {
    openedMenus.value.push(item.path)
  }
  // 保存展开的子菜单状态
  localStorage.setItem('agentOpenedMenus', JSON.stringify(openedMenus.value))
}

// 导航到指定路径
const navigateTo = (path: string) => {
  router.push(path)
}

// 切换用户下拉菜单
const toggleUserDropdown = () => {
  isUserDropdownOpen.value = !isUserDropdownOpen.value
}

// 查看个人信息
const viewProfile = () => {
  router.push('/agent/profile')
  isUserDropdownOpen.value = false
}

// 查看账户设置
const viewSettings = () => {
  router.push('/agent/profile')
  isUserDropdownOpen.value = false
}

// 退出登录
const logout = () => {
  // 执行登出操作
  console.log('退出登录')
  isUserDropdownOpen.value = false
  router.push('/login')
}

// 监听路由变化，自动展开对应子菜单
watch(
  () => route.path,
  (newPath) => {
    for (const item of menuItems) {
      if (item.children && item.children.some(child => child.path === newPath)) {
        if (!openedMenus.value.includes(item.path)) {
          openedMenus.value.push(item.path)
          localStorage.setItem('agentOpenedMenus', JSON.stringify(openedMenus.value))
        }
      }
    }

    // 点击其他地方关闭用户下拉菜单
    isUserDropdownOpen.value = false
  }
)

// 组件挂载时，从本地存储中获取菜单折叠状态
onMounted(() => {
  // 恢复菜单折叠状态
  const savedState = localStorage.getItem('agentMenuCollapsed')
  if (savedState !== null) {
    isCollapsed.value = savedState === 'true'
  }

  // 恢复展开的子菜单状态
  const savedOpenedMenus = localStorage.getItem('agentOpenedMenus')
  if (savedOpenedMenus) {
    try {
      openedMenus.value = JSON.parse(savedOpenedMenus)
    } catch (e) {
      console.error('解析保存的子菜单状态失败', e)
    }
  }

  // 根据当前路径自动展开对应子菜单
  for (const item of menuItems) {
    if (item.children && item.children.some(child => child.path === route.path)) {
      if (!openedMenus.value.includes(item.path)) {
        openedMenus.value.push(item.path)
      }
    }
  }

  // 添加全局点击事件监听，点击外部关闭用户下拉菜单
  document.addEventListener('click', (e) => {
    if (isUserDropdownOpen.value) {
      const dropdown = document.querySelector('.dropdown')
      if (dropdown && !dropdown.contains(e.target as Node)) {
        isUserDropdownOpen.value = false
      }
    }
  })
})
</script>

<style scoped lang="scss">
.agent-layout {
  display: flex;
  height: 100vh;
  width: 100%;
  overflow: hidden;
}

/* 侧边栏样式 */
.sidebar {
  width: 260px;
  background: linear-gradient(180deg, #1e293b 0%, #0f172a 100%);
  color: #f8fafc;
  transition: all 0.3s;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  flex-shrink: 0;
  box-shadow: 4px 0 15px rgba(0, 0, 0, 0.08);
  z-index: 10;
  /* 确保侧边栏在内容上方 */
}

.sidebar.collapsed {
  width: 64px;
}

.logo {
  padding: 20px;
  text-align: center;
  border-bottom: 1px solid #334155;
  background-color: #0f172a;
}

.logo h2 {
  margin: 0;
  font-size: 1.5rem;
  white-space: nowrap;
  font-weight: 600;
  background: linear-gradient(45deg, #38bdf8, #818cf8);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.menu {
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
}

.menu-item {
  margin-bottom: 2px;
  transition: all 0.3s;
  white-space: nowrap;
}

.menu-item-title {
  padding: 12px 20px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 8px;
  margin: 0 10px;

  &:hover {
    background-color: rgba(51, 65, 85, 0.7);
  }
}

.menu-item.active>.menu-item-title {
  background: linear-gradient(90deg, #3b82f6, #38bdf8);
  color: white;
  box-shadow: 0 4px 10px rgba(59, 130, 246, 0.3);
}

.menu-item .icon {
  margin-right: 10px;
  width: 20px;
  text-align: center;
}

.submenu-arrow {
  margin-left: auto;
  transition: transform 0.3s;
}

.submenu {
  overflow: hidden;
  background-color: rgba(15, 23, 42, 0.7);
  margin: 0 10px;
  border-radius: 8px;
}

.submenu-item {
  padding: 10px 20px 10px 50px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s;
  border-radius: 6px;
  margin: 4px 6px;
}

.submenu-item:hover {
  background-color: rgba(30, 41, 59, 0.7);
}

.submenu-item.active {
  background: linear-gradient(90deg, #3b82f6, #38bdf8);
  color: white;
}

.submenu-item .icon {
  margin-right: 10px;
  width: 16px;
  text-align: center;
}

.collapse-button {
  padding: 15px 20px;
  text-align: center;
  cursor: pointer;
  border-top: 1px solid #334155;
  transition: all 0.3s;
}

.collapse-button:hover {
  background-color: #334155;
}

/* 主内容区域样式 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f8fafc;
  position: relative;
  /* 确保内容区域可以滚动 */
}

.header {
  height: 64px;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);
  z-index: 5;
  /* 头部应在内容上方但在侧边栏下方 */
  border-bottom: 1px solid rgba(226, 232, 240, 0.7);
  flex-shrink: 0;
  /* 防止header被压缩 */
}

.breadcrumb {
  font-size: 16px;
  color: #334155;
}

.breadcrumb-item.clickable {
  cursor: pointer;
  color: #3b82f6;
  font-weight: 500;
}

.breadcrumb-item.clickable:hover {
  text-decoration: underline;
}

.breadcrumb-separator {
  margin: 0 8px;
  color: #cbd5e1;
}

.user-info {
  display: flex;
  align-items: center;
}

.username {
  margin-right: 10px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  color: #334155;
  padding: 8px 12px;
  border-radius: 8px;
  transition: all 0.2s;

  &:hover {
    background-color: #f1f5f9;
  }
}

.username .icon {
  margin-left: 6px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #e2e8f0;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
  transition: all 0.2s;

  &:hover {
    transform: scale(1.05);
    box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
  }
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.dropdown {
  position: relative;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 10px;
  min-width: 200px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
  z-index: 10;
  overflow: hidden;
  animation: dropdown-fade 0.2s ease-out;
  border: 1px solid rgba(226, 232, 240, 0.7);
}

@keyframes dropdown-fade {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.dropdown-item {
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  color: #334155;
}

.dropdown-item:hover {
  background-color: #f1f5f9;
}

.dropdown-item .icon {
  margin-right: 10px;
  width: 16px;
  color: #64748b;
}

.dropdown-divider {
  height: 1px;
  background-color: #e2e8f0;
  margin: 4px 0;
}

.content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  overflow-x: hidden;
  /* 防止水平滚动 */
  height: calc(100vh - 64px);
  /* 确保内容区域高度正确 */
  position: relative;
}

/* 状态标签修复 */
:deep(.status-tag) {
  display: inline-flex;
  align-items: center;
  padding: 6px 10px;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 500;

  &:before {
    content: '';
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 6px;
  }

  &.status-active {
    background-color: rgba(16, 185, 129, 0.1);
    color: #10b981;

    &:before {
      background-color: #10b981;
    }
  }

  &.status-inactive {
    background-color: rgba(239, 68, 68, 0.1);
    color: #ef4444;

    &:before {
      background-color: #ef4444;
    }
  }

  &.status-pending {
    background-color: rgba(245, 158, 11, 0.1);
    color: #f59e0b;

    &:before {
      background-color: #f59e0b;
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    z-index: 10;
    height: 100vh;
    box-shadow: 2px 0 20px rgba(0, 0, 0, 0.15);
    transform: translateX(0);
  }

  .sidebar.collapsed {
    transform: translateX(-260px);
  }

  .main-content {
    margin-left: 0;
  }

  .header {
    padding: 0 16px;
  }

  .content {
    padding: 16px;
    height: calc(100vh - 64px);
    /* 确保在移动设备上内容区域高度正确 */
  }
}

/* IE11 兼容性修复 */
@media screen and (-ms-high-contrast: active),
(-ms-high-contrast: none) {
  .agent-layout {
    display: -ms-flexbox;
    -ms-flex-direction: row;
  }

  .sidebar {
    display: -ms-flexbox;
    -ms-flex-direction: column;
    -ms-flex: 0 0 260px;
  }

  .sidebar.collapsed {
    -ms-flex: 0 0 64px;
  }

  .menu {
    -ms-flex: 1 1 auto;
  }

  .main-content {
    display: -ms-flexbox;
    -ms-flex-direction: column;
    -ms-flex: 1 1 auto;
  }

  .header {
    display: -ms-flexbox;
    -ms-flex-pack: justify;
    -ms-flex-align: center;
  }

  .user-info {
    display: -ms-flexbox;
    -ms-flex-align: center;
  }

  .dropdown-menu {
    top: 100%;
  }

  .content {
    -ms-flex: 1 1 auto;
  }
}

/* 页面过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
